package com.vimi8.ebb.auth.manage;

import com.vimi8.ebb.auth.model.MessageParam;
import com.vimi8.ebb.auth.utils.CommonUtil;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by think on 2017/1/16.
 */
@Service
public class PushManageImpl implements PushManage{
    private Logger logger =  LoggerFactory.getLogger(this.getClass());
    @Override
    public boolean isPushMessageToXinGeSuccess(MessageParam messageParam) throws Exception {

            String authCode="";
            // 创建默认的httpClient实例.
            CloseableHttpClient httpclient = HttpClients.createDefault();
            //http://v.juhe.cn/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
           // String tplValue= URLEncoder.encode(smsParam.getTplValue(),"UTF-8");
         // http://接口域名/v2/push/single_account?params
            String url="http://openapi.xg.qq.com/v2/push/single_account";
            logger.info("url param="+url);
         //  account message_type  message
        // POSTopenapi.xg.qq.com/v2/push/single_device Param1=Value1Param2=Value2access_id=123timestamp=1386691200abcde
        //ACCESS KEY ARHI967N29TU  ACCESS ID 2100246147
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("POSTopenapi.xg.qq.com/v2/push/single_account");
        messageParam.setAccessId("2100246147");
        stringBuilder.append("access_id="+messageParam.getAccessId());
        stringBuilder.append("account="+messageParam.getAccount());
        stringBuilder.append("message="+messageParam.getMessage());
        stringBuilder.append("message_type="+messageParam.getMessageType());

        stringBuilder.append("timestamp="+messageParam.getTimestamp());
        stringBuilder.append("ARHI967N29TU");
        String sign= CommonUtil.MD5(stringBuilder.toString());
        logger.info("sign="+sign);
        messageParam.setSign(sign);

        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("account", messageParam.getAccount()));
        nvps.add(new BasicNameValuePair("message_type", messageParam.getMessageType()));
        nvps.add(new BasicNameValuePair("message", messageParam.getMessage()));
        nvps.add(new BasicNameValuePair("sign",messageParam.getSign()));
        nvps.add(new BasicNameValuePair("access_id",messageParam.getAccessId()));
        nvps.add(new BasicNameValuePair("timestamp ",messageParam.getTimestamp().toString()));
        logger.info("messageParam="+messageParam.toString());
        CloseableHttpResponse response = httpclient.execute(httpost);
        String result=null;
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            result= EntityUtils.toString(entity);
            logger.info("result="+result);
            // {    “ret_code”:0,    “err_msg”:”ok”,    “result”:{“status”:0} }
            //返
            EntityUtils.consume(entity);
            JSONObject jsonObject=new JSONObject();
            if(!StringUtils.isEmpty(result)){
                 jsonObject=JSONObject.fromObject(result);
            }
            if(jsonObject.containsKey("ret_code")){
                int retCode=jsonObject.optInt("ret_code");
                if(0==retCode){
                    return true;
                }else{
                    String errorStr=jsonObject.optString("err_msg");
                    throw new Exception(errorStr);
                }

            }

        } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage());
        }
        return false;
    }
}
